#!/bin/bash
# Generate Cordova icons

function usage() {
	echo "usage: $0 <image-filename> [output-directory]";
	exit 1;
}

[ "$1" ] || usage
[ "$2" ] || set "$1" "."

image=$1
output=$2/resources/icon

devices=ios,android #,windows-phone,bada,bada-wac,blackberry,webos
eval mkdir -p "$output/{$devices}"

# Show the user some progress by outputing all commands being run.
set -x

# Explicitly set background in case image is transparent (see: #3)
convert="convert $image -background none"

function androidConvertIcon() {
	drawables=drawable,drawable-ldpi,drawable-mdpi,drawable-hdpi,drawable-xhdpi
	eval mkdir -p "$output/android/{$drawables}"

	$convert -resize 36x36 "$output/android/drawable-ldpi/icon.png"
	$convert -resize 48x48 "$output/android/drawable-mdpi/icon.png"
	$convert -resize 72x72 "$output/android/drawable-hdpi/icon.png"
	$convert -resize 96x96 "$output/android/drawable-xhdpi/icon.png"
	$convert -resize 96x96 "$output/android/drawable/icon.png"

	function androidCopyIcon() {
		androidOutput=$(find . -type d | grep "platforms/android/res$")
		find . -type d | grep "resources/icon/android/drawable" | xargs -I{} cp -R {} $androidOutput
	}
	androidCopyIcon
}
androidConvertIcon

function iosConvertIcon() {
	$convert -resize 29x29 "$output/ios/icon-small.png"
	$convert -resize 40x40 "$output/ios/icon-40.png"
	$convert -resize 50x50 "$output/ios/icon-50.png"
	$convert -resize 57x57 "$output/ios/icon.png"
	$convert -resize 58x58 "$output/ios/icon-small@2x.png"
	$convert -resize 60x60 "$output/ios/icon-60.png"
	$convert -resize 72x72 "$output/ios/icon-72.png"
	$convert -resize 76x76 "$output/ios/icon-76.png"
	$convert -resize 80x80 "$output/ios/icon-40@2x.png"
	$convert -resize 100x100 "$output/ios/icon-50@2x.png"
	$convert -resize 114x114 "$output/ios/icon@2x.png"
	$convert -resize 120x120 "$output/ios/icon-60@2x.png"
	$convert -resize 144x144 "$output/ios/icon-72@2x.png"
	$convert -resize 152x152 "$output/ios/icon-76@2x.png"
	$convert -resize 512x512 "$output/ios/iTunesArtwork.png"
	$convert -resize 1024x1024 "$output/ios/iTunesArtwork@2x.png"

	function iosCopyIcon() {
		cp $(find . | grep "resources/icon/ios/.*\.png") "$(find . -type d | grep 'platforms/ios/.*Resources/icons')"
	}
	iosCopyIcon
}
iosConvertIcon
